package qdu.guisockets.serverlet;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class TestSocketServer {
    static ServerSocket ss;
    static List<ClientHandler> clientList;
    private ServerUI serverUI;
    public TestSocketServer(ServerUI serverUI){
        this.serverUI = serverUI;
        clientList = new ArrayList<ClientHandler>();        
    }
  
    static void updateOtherClients(String resultMessage, ClientHandler thisHandler) throws IOException{
        for(ClientHandler index : clientList){
            if(!(index == thisHandler)){
                if(index != null && !index.getClientSocket().isClosed()){
                    index.getBw().write(resultMessage + '\n');
                    index.getBw().flush();
                }
            }
        }
    }
    static void updateOtherClients(String resultMessage) throws IOException{
        for(ClientHandler index : clientList)          
            if(index != null && !index.getClientSocket().isClosed()){
                index.getBw().write(resultMessage + '\n');
                index.getBw().flush();
            }
    }
    void initServer(){
        try {
            ss = new ServerSocket(9999);
        } catch (IOException e) {
            System.out.println("服务端Socket创建错误"); System.exit(0); //e.printStackTrace();
        }
        try{
            while(true){
                Socket clinetSocket = ss.accept();
                if(clientList!= null){
                    ClientHandler ch = new ClientHandler(clinetSocket, serverUI);
                    ch.start();
                    clientList.add(ch);
                    String msg = "客户端IP:" + clinetSocket.getInetAddress() + "端口:" + clinetSocket.getPort() + "进入聊天室";
                    serverUI.appendTf1Msg(msg);
                    updateOtherClients(msg, ch);
                }
            }
        }catch(IOException e){
            System.out.println("服务端监听出错");            
            System.exit(0);
        }
    }
}
